package com.lindroy.androidplayer.utils

import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.annotation.DrawableRes
import androidx.core.view.isGone
import androidx.core.view.isInvisible
import androidx.core.view.isVisible
import androidx.databinding.BindingAdapter
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import coil.load
import com.elvishew.xlog.XLog
import com.lindroy.androidplayer.R
import com.lindroy.androidplayer.logic.network.enums.LayoutState
import com.lindroy.androidplayer.ui.widget.CustomSwipeRefreshLayout
import com.lindroy.androidplayer.ui.widget.SettingBar
import com.lindroy.multistatelayout.widget.FrameStateLayout

/**
 * @author Lin
 * @date 2022/1/12
 * @function
 */

@BindingAdapter("imageUrl")
fun loadImageUrl(imageView: ImageView, url: String?) {
    XLog.d("imageUrl : $url")
    imageView.load(url) {
        placeholder(R.drawable.img_placeholder)
    }
}

@BindingAdapter("drawableRes")
fun setDrawableRes(imageView: ImageView, @DrawableRes drawableId: Int) {
    imageView.setImageResource(drawableId)
}

@BindingAdapter("isVisible")
fun isVisible(view: View, isVisible: Boolean) {
    view.isVisible = isVisible
}

@BindingAdapter("isInVisible")
fun isInVisible(view: View, isInVisible: Boolean) {
    view.isInvisible = isInVisible
}

@BindingAdapter("isGone")
fun isGone(view: View, isGone: Boolean) {
    view.isGone = isGone
}

@BindingAdapter("isSelected")
fun isSelected(view: View, isSelected: Boolean) {
    view.isSelected = isSelected
}

@BindingAdapter("isRefresh")
fun setRefresh(swipeRefreshLayout: SwipeRefreshLayout, isRefresh: Boolean?) {
    swipeRefreshLayout.isRefreshing = isRefresh ?: false
}

@BindingAdapter("refreshListener")
fun setRefreshListener(
    swipeRefreshLayout: CustomSwipeRefreshLayout,
    listener: SwipeRefreshLayout.OnRefreshListener
) {
    swipeRefreshLayout.setOnRefreshListener(listener)
}

@BindingAdapter("htmlText")
fun setHtmlText(textView: TextView, title: String?) {
    if (title == null) {
        textView.text = ""
        return
    }
    textView.text = title.toHtml()
}

@BindingAdapter("state")
fun setState(stateLayout: FrameStateLayout, state: Int) {
    stateLayout.apply {
        when (state) {
            LayoutState.LOADING -> showLoading()
            LayoutState.CONTENT -> showContent()
            LayoutState.EMPTY -> showEmpty()
            LayoutState.REFRESH -> showContent()
            LayoutState.NO_NETWORK -> showNoNetwork()
            LayoutState.SERVER_ERROR -> showError()
            LayoutState.NOT_LOGIN -> showStateView(LayoutState.NOT_LOGIN)
            else -> showContent()
        }
    }
}

@BindingAdapter("sb_checked")
fun setChecked(view: SettingBar, isCheck: Boolean) {
    view.setSwitchChecked(isCheck)
}

@BindingAdapter("sb_desc")
fun setSettingBarDesc(view: SettingBar, desc: String?) {
    //这里的 desc 声明为可空，因为第一次总会收到一个空值，原因未明
    view.setDesc(desc)
}



